package com.dd.cloud.user.service.chknowl.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.FileConstants;
import com.dd.cloud.user.entity.chknowl.*;
import com.dd.cloud.user.entity.file.FileInfo;
import com.dd.cloud.user.req.chknowl.*;
import com.dd.cloud.user.res.chknowl.*;
import com.dd.cloud.user.service.chknowl.IChknowlChDrugsCategoryService;
import com.dd.cloud.user.service.chknowl.IChknowlChDrugsTropismLinkService;
import com.dd.cloud.user.service.chknowl.IChkonwlChDrugsTropismService;
import com.dd.cloud.user.service.file.IFileInfoService;
import com.dd.cloud.user.util.HuaWeiOBSUtil;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.dd.cloud.common.constants.ChKnowlConstants;
import com.dd.cloud.common.constants.SearchConstants;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.user.mapper.chknowl.ChknowlChDrgusMapper;
import com.dd.cloud.user.service.chknowl.IChknowlChDrgusService;
import com.dd.cloud.user.service.search.ISearchHotService;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 古籍中药材 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-07-04
 */
@Service
@Slf4j
public class ChknowlChDrgusServiceImpl extends ServiceImpl<ChknowlChDrgusMapper, ChknowlChDrugs> implements IChknowlChDrgusService {

    @Autowired
    public FastFileStorageClient storageClient;
    @Autowired
    private ISearchHotService searchHotService;

    @Autowired
    private IChknowlChDrugsCategoryService categoryService;

    @Autowired
    private IChkonwlChDrugsTropismService ckonwlChDrugsTropismService;


    @Autowired
    private IChknowlChDrugsTropismLinkService chDrugsTropismLinkService;

    @Autowired
    private IFileInfoService fileInfoService;


    /**
     * 分页查询中药材说明
     *
     * @param req 条件参数
     * @return
     */
    @Override
    public IPage<ChknowlChDrugsPageRes> queryChDrugsPage(ChDrugsQueryReq req) {
        IPage<ChknowlChDrugsPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().getChDrugsPage(iPage, req);
        return iPage;
    }

    /**
     * 通过id查询中药材的详细信息
     *
     * @param id id
     * @return
     */
    @Override
    public ChknowlChDrugsDetailRes queryChDrugsDetail(Integer id) {
        ChknowlChDrugsDetailRes md = getBaseMapper().getChDrugsDetailById(id);
        if (md != null && StringUtils.isNotBlank(md.getTropism())) {
            String tropism = md.getTropism().replace("经", "");
            log.info("转换之后的归经:{}", tropism);
            md.setTropism("归" + tropism + "经");

        }
        return md;
    }

    /**
     * 添加中药材
     *
     * @param req 参数
     */
    @Override
    public void createChDrugs(ChDrugsCreateReq req) {
//        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
//        QueryWrapper<ChknowlChDrugs> qq = new QueryWrapper<>();
//        qq.lambda().select(ChknowlChDrugs::getName)
//                .eq(ChknowlChDrugs::getName, req.getName())
//                .ne(ChknowlChDrugs::getStatus, ChKnowlConstants.ContentStatus.DELETE);
//        ChknowlChDrugs chknowlChDrugs = getOne(qq);
//        if (chknowlChDrugs != null) {
//            throw new ZekeException(400, req.getName() + "药材已存在");
//        }
//        if (!ObjectUtils.refrect(ChKnowlConstants.ContentStatus.class, req.getStatus())) {
//            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
//        }
//        ChknowlChDrugs md = new ChknowlChDrugs();
//        BeanUtils.copyProperties(req, md);
//        md.setNamePinyin(PinYinUtils.chineseToPinyin(md.getName()));
//        if (req.getSort() == null || req.getSort() < 1) {
//            QueryWrapper<ChknowlChDrugs> qw = new QueryWrapper<>();
//            qw.lambda().orderByDesc(ChknowlChDrugs::getSort);
//            qw.lambda().select(ChknowlChDrugs::getSort);
//            qw.last("limit 1");
//            ChknowlChDrugs temp = getOne(qw);
//            if (temp == null || temp.getSort() == null) {
//                md.setSort(1);
//            } else {
//                md.setSort(temp.getSort() + 1);
//            }
//        } else {
//            UpdateWrapper<ChknowlChDrugs> uw = new UpdateWrapper<>();
//            uw.lambda().ge(ChknowlChDrugs::getSort, req.getSort());
//            uw.setSql("sort = sort + 1");
//            update(uw);
//        }
//        md.setCreateDate(LocalDateTime.now());
////        md.setOperDate(LocalDateTime.now());
////        md.setOperId(loginInfo.getId());
//        boolean flag = save(md);
//        if (!flag) {
//            throw new ZekeException(400, "添加中药材信息失败");
//        }
    }

    /**
     * 修改中药材
     *
     * @param req 参数
     */
    @Override
    public void updateChDrugs(ChDrugsUpdateReq req) {
//        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
//        ChknowlChDrugs mpd = getById(req.getId());
//        if (mpd == null || mpd.getStatus() == ChKnowlConstants.ContentStatus.DELETE) {
//            throw new ZekeException(400, "中成药信息不存在");
//        }
//        if (!mpd.getName().equals(req.getName())) {
//            //修改了药品名, 判断药品名是否存在
//            QueryWrapper<ChknowlChDrugs> qw = new QueryWrapper<>();
//            qw.lambda().eq(ChknowlChDrugs::getName, req.getName())
//                    .select(ChknowlChDrugs::getId)
//                    .ne(ChknowlChDrugs::getStatus, ChKnowlConstants.ContentStatus.DELETE);
//            ChknowlChDrugs patent = getOne(qw);
//            if (patent != null) {
//                throw new ZekeException(400, "药品名已存在");
//            }
//        }
//        if (!ObjectUtils.refrect(ChKnowlConstants.ContentStatus.class, req.getStatus())) {
//            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
//        }
//        ChknowlChDrugs md = new ChknowlChDrugs();
//        BeanUtils.copyProperties(req, md);
//        md.setNamePinyin(PinYinUtils.chineseToPinyin(md.getName()));
////        md.setOperId(loginInfo.getId());
////        md.setOperDate(LocalDateTime.now());
//        if (req.getSort() == null || req.getSort() < 1) {
//            QueryWrapper<ChknowlChDrugs> qw = new QueryWrapper<>();
//            qw.lambda().orderByDesc(ChknowlChDrugs::getSort);
//            qw.lambda().select(ChknowlChDrugs::getSort);
//            qw.last("limit 1");
//            ChknowlChDrugs temp = getOne(qw);
//            if (temp == null || temp.getSort() == null) {
//                md.setSort(1);
//            } else {
//                md.setSort(temp.getSort() + 1);
//            }
//        } else {
//            QueryWrapper<ChknowlChDrugs> qw = new QueryWrapper<>();
//            qw.lambda().eq(ChknowlChDrugs::getId, req.getId());
//            qw.lambda().select(ChknowlChDrugs::getSort);
//            ChknowlChDrugs temp = getOne(qw);
//            if (!temp.getSort().equals(req.getSort())) {
//                UpdateWrapper<ChknowlChDrugs> uw = new UpdateWrapper<>();
//                uw.lambda().ge(ChknowlChDrugs::getSort, req.getSort());
//                uw.setSql("sort = sort + 1");
//                update(uw);
//            }
//        }
//        boolean flag = updateById(md);
//        if (!flag) {
//            throw new ZekeException(400, "修改中药材信息失败");
//        }
    }

    /**
     * 修改中药材状态
     *
     * @param id     id
     * @param status 状态
     */
    @Override
    public void updateChDrugsStatus(Integer id, Integer status) {
        ChknowlChDrugs md = getById(id);
        if (md == null) {
            throw new ZekeException(400, "药品id不存在");
        }
        if (!ObjectUtils.refrect(ChKnowlConstants.ContentStatus.class, status)) {
            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
        }
        md.setStatus(status);
        boolean flag = updateById(md);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
    }

    /**
     * 从Excel批量导入中药材数据
     *
     * @param file excel文件
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void importMiddleDrugs(MultipartFile file) {
        if (file == null) {
            throw new ZekeException(400, "请上传文件");
        }
        if (!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            throw new ZekeException(400, "只支持xlsx和xls文件格式");
        }
        List<ChknowlChDrugs> list = new ArrayList<>();
        try {
            list = ExtUtils.importExcel(file, 0, 1, ChknowlChDrugs.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }

        if (list == null || list.isEmpty()) {
            throw new ZekeException(400, "文档数据为空");
        }
        List<String> exists = getBaseMapper().getChknowlChDrugsNameIsExists(list.stream().map(ChknowlChDrugs::getName).collect(Collectors.toList()));
        if (exists != null && !exists.isEmpty()) {
            throw new ZekeException(400, "以下药品名已存在:" + StringUtils.join(exists, ","));
        }

        list.stream().forEach(drugsChineseExplain -> {
            ValidatorUtils.verify(drugsChineseExplain, ChknowlChDrugs.class);
            drugsChineseExplain.setCreateDate(LocalDateTime.now());
            drugsChineseExplain.setStatus(ChKnowlConstants.ContentStatus.NORMAL);
            if (!StringUtils.isBlank(drugsChineseExplain.getImgUrl())) {
                try {
                    File f = new File(drugsChineseExplain.getImgUrl());
                    InputStream fis = new FileInputStream(f);
                    MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), "image/jpg", IOUtils.toByteArray(fis));
                    String imgUrl = UploadUtil.uploadImage(multipartFile, storageClient);
                    drugsChineseExplain.setImgUrl(imgUrl);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new ZekeException(400, "文档图片下载失败");
                }
            }
        });
        Integer flag = getBaseMapper().insertBatchSomeColumn(list);
        if (flag <= 0) {
            throw new ZekeException(400, "批量导入数据失败");
        }
    }

    /**
     * 关键字查询中药材信息
     *
     * @param keyword
     * @return
     */
    @Override
    public List<ChUserSearchListRes> getChDrugsListByKeyword(String keyword) {
        //添加热门搜索
        searchHotService.saveSearchHot(SearchConstants.Modular.CHSCIENCE, SearchConstants.ChscienceSubmodule.CHINESE, keyword);
        List<ChUserSearchListRes> list = getBaseMapper().getChDrugsListByKeyword(keyword);
        return list;
    }

    @Override
    public List<ChkonwlDrugsRes> queryDrugsList(ChkonwlDrugsReq chkonwlDrugsReq) {
        List<ChkonwlDrugsRes> res = null;
        //根据条件筛选药品
        if (StringUtils.isNotBlank(chkonwlDrugsReq.getTropisms())) {
            String[] tropismArray = chkonwlDrugsReq.getTropisms().split(",");
            chkonwlDrugsReq.setTropismArray(tropismArray);
        }
        if (StringUtils.isNotBlank(chkonwlDrugsReq.getNatures())) {
            String[] natureArray = chkonwlDrugsReq.getNatures().split(",");
            chkonwlDrugsReq.setNatureArray(natureArray);
        }
        if (StringUtils.isNotBlank(chkonwlDrugsReq.getFlavours())) {
            String[] flavoursArray = chkonwlDrugsReq.getFlavours().split(",");
            chkonwlDrugsReq.setFlavourArray(flavoursArray);
        }
        //查询药品
        List<ChknowlChDrugs> drugsList = this.getBaseMapper().queryDrugsList(chkonwlDrugsReq.getNatureArray(),
                chkonwlDrugsReq.getFlavourArray(),
                chkonwlDrugsReq.getTropismArray());
        if (CollectionUtil.isNotEmpty(drugsList)) {
            List<Integer> oneCategoryId = getLevelCategory(drugsList, 1, 1);
            List<Integer> twoCategoryId = getLevelCategory(drugsList, 2, 1);
            //二级分类的父id
            List<Integer> oneAndTwoCategoryId = getLevelCategory(drugsList, 2, 2);
            String oneCategoryIdStr = StringUtils.join(oneCategoryId.toArray(), ",");
            if (CollectionUtil.isNotEmpty(oneAndTwoCategoryId)) {
                String pidCategoryIdStr = StringUtils.join(oneAndTwoCategoryId.toArray(), ",");
                if (StringUtils.isNotBlank(oneCategoryIdStr)) {
                    oneCategoryIdStr = oneCategoryIdStr + "," + pidCategoryIdStr;
                } else {
                    oneCategoryIdStr = pidCategoryIdStr;
                }
            }
            String twoCategoryIdStr = "-1";
            if (CollectionUtil.isNotEmpty(twoCategoryId)) {
                twoCategoryIdStr = StringUtils.join(twoCategoryId.toArray(), ",");
            }
            res = this.getBaseMapper().queryCategoryList(oneCategoryIdStr, twoCategoryIdStr);
            Map<Integer, List<ChknowlChDrugs>> drugsMap = getDrugsList(drugsList);
            if (CollectionUtil.isNotEmpty(res)) {
                for (ChkonwlDrugsRes item : res) {
                    List<ChkonwlDrugsRes> chknowlDrugsChild = item.getChknowlDrugChild();
                    if (CollectionUtil.isNotEmpty(chknowlDrugsChild)) {
                        item.setIsChild(true);
                        for (ChkonwlDrugsRes child : chknowlDrugsChild) {
                            List<ChknowlChDrugs> chknowlDrugsList = drugsMap.get(child.getCategoryId());
                            child.setChknowlDrugsList(chknowlDrugsList);
                            child.setIsChild(false);
                        }
                    } else {
                        item.setIsChild(false);
                        List<ChknowlChDrugs> chknowlChDrugsList = drugsMap.get(item.getCategoryId());
                        item.setChknowlDrugsList(chknowlChDrugsList);
                    }
                }
            }
        }
        return res;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDrugBatch(MultipartFile file) {
        if (file == null) {
            throw new ZekeException(400, "请上传文件");
        }
        if (!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            throw new ZekeException(400, "只支持xlsx和xls文件格式");
        }
        List<ExcelAddDrugsModel> list = new ArrayList<>();
        try {
            list = ExtUtils.importExcel(file, 0, 1, ExcelAddDrugsModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }

        if (list == null || list.isEmpty()) {
            throw new ZekeException(400, "文档数据为空");
        }
        for (ExcelAddDrugsModel model : list) {
            String category = model.getCategory().trim();
            String[] categories = category.split("-");
            Integer categoryId = null;
            if (categories.length == 1) {
                //一级
                categoryId = queryDrugsOneCategoryId(categories);
            } else if (categories.length == 2) {
                //一级
                categoryId = queryDrugsOneCategoryId(categories);
                //二级
                categoryId = queryDrugsTwoCategoryId(categories, categoryId);
            }
            ChknowlChDrugs chknowlChDrug = new ChknowlChDrugs();
            chknowlChDrug.setAlias(model.getAlias())
                    .setName(model.getName().trim())
                    .setDosage(model.getDosage())
                    .setCreateDate(LocalDateTime.now())
                    .setIntroduction(model.getIntroduction())
                    .setPrecautions(model.getPrecautions())
                    .setStatus(1)
                    .setIndications(model.getIndications())
//                    .setSort(model.getSort())
                    .setCategoryId(categoryId)
                    .setDrugName(model.getDrugName());
            //导入性
            if (StringUtils.isNotBlank(model.getNature())) {
                chknowlChDrug.setNature(model.getNature().trim());
            }
            //导入味
            if (StringUtils.isNotBlank(model.getFlavour())) {
                chknowlChDrug.setFlavour(model.getFlavour().trim());
            }
            chknowlChDrug.setNamePinyin(PinYinUtils.chineseToPinyin(chknowlChDrug.getName()));
            //导入归经
            String tropism = model.getTropism();
            if (StringUtils.isNotBlank(tropism)) {
                String[] tropismNames = tropism.split("/");
                if (tropismNames.length == 1) {
                    String[] tropisms = tropismNames[0].trim().split("、");
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < tropisms.length; i++) {
                        if (tropisms.length - 1 == i) {
                            sb.append(tropisms[i].trim());
                            sb.append("经");
                        } else {
                            sb.append(tropisms[i].trim());
                            sb.append("经、");
                        }
                    }
                    chknowlChDrug.setTropism(sb.toString());
                } else if (tropismNames.length == 2) {
                    chknowlChDrug.setOtherData(tropismNames[0].trim());
                    String[] tropisms = tropismNames[1].trim().split("、");
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < tropisms.length; i++) {
                        if (tropisms.length - 1 == i) {
                            sb.append(tropisms[i].trim());
                            sb.append("经");
                        } else {
                            sb.append(tropisms[i].trim());
                            sb.append("经、");
                        }
                    }
                    chknowlChDrug.setTropism(sb.toString());
                }
            }
            this.save(chknowlChDrug);
        }
    }

//    private Integer getTropismId(String name, int type) {
//        Integer tropismId = null;
//        LambdaQueryWrapper<ChkonwlChDrugsTropism> chkonwlChDrugsTropismLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        chkonwlChDrugsTropismLambdaQueryWrapper
//                .eq(ChkonwlChDrugsTropism::getType, type)
//                .eq(ChkonwlChDrugsTropism::getName, name)
//                .eq(ChkonwlChDrugsTropism::getStatus, 1)
//                .last("limit 1");
//        ChkonwlChDrugsTropism chkonwlChDrugsTropism = ckonwlChDrugsTropismService.getOne(chkonwlChDrugsTropismLambdaQueryWrapper);
//        if (chkonwlChDrugsTropism == null) {
//            ChkonwlChDrugsTropism tropism = new ChkonwlChDrugsTropism();
//            LambdaQueryWrapper<ChkonwlChDrugsTropism> sortWrapper = new LambdaQueryWrapper<>();
//            chkonwlChDrugsTropismLambdaQueryWrapper
//                    .eq(ChkonwlChDrugsTropism::getType, type)
//                    .eq(ChkonwlChDrugsTropism::getStatus, 1)
//                    .orderByDesc(ChkonwlChDrugsTropism::getSort)
//                    .last("limit 1");
//            ChkonwlChDrugsTropism sortObject = ckonwlChDrugsTropismService.getOne(sortWrapper);
//            if (sortObject == null) {
//                tropism.setSort(1);
//            } else {
//                tropism.setSort(sortObject.getSort() + 1);
//            }
//            tropism.setType(type).setName(name).setStatus(1).setCreateDate(LocalDateTime.now());
//            ckonwlChDrugsTropismService.save(tropism);
//            tropismId = tropism.getId();
//            log.info("tropismId:{}", tropismId);
//        } else {
//            tropismId = chkonwlChDrugsTropism.getId();
//        }
//        return tropismId;
//    }

    @Override
    public void addDrugUrl(MultipartFile[] files) {
        List<ChknowlChDrugs> chknowlChDrugList = new ArrayList<>();
        for (int j = 0; j < files.length; j++) {
            String originalFilename = files[j].getOriginalFilename();
            String[] strs = originalFilename.split("-");
            String[] imgName = strs[1].split("\\.");
            LambdaQueryWrapper<ChknowlChDrugs> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChknowlChDrugs::getName, imgName[0])
                    .eq(ChknowlChDrugs::getStatus, 1);
            List<ChknowlChDrugs> chknowlChDrugs = this.list(wrapper);
            if (chknowlChDrugs.size() != 1) {
                log.info("-----无法处理---" + imgName[0]);
                continue;
            }
            ChknowlChDrugs chknowlChDrug = chknowlChDrugs.get(0);
            String imgUrl = HuaWeiOBSUtil.uploadFile(files[j]);
            chknowlChDrug.setImgUrl(imgUrl);
            chknowlChDrugList.add(chknowlChDrug);
        }
        if (CollectionUtil.isNotEmpty(chknowlChDrugList)) {
            boolean flag = this.updateBatchById(chknowlChDrugList);
            if (!flag) {
                throw new ZekeException("保存中药图片路径失败!");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDrugOther(MultipartFile file) {
        if (file == null) {
            throw new ZekeException(400, "请上传文件");
        }
        if (!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            throw new ZekeException(400, "只支持xlsx和xls文件格式");
        }
        List<ExcelAddTropismModel> list = new ArrayList<>();
        try {
            list = ExtUtils.importExcel(file, 0, 1, ExcelAddTropismModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }

        if (list == null || list.isEmpty()) {
            throw new ZekeException(400, "文档数据为空");
        }
        List<ChkonwlChDrugsTropism> chDrugsTropismList = new ArrayList<>();
        for (ExcelAddTropismModel model : list) {
            ChkonwlChDrugsTropism chkonwlChDrugsTropism = new ChkonwlChDrugsTropism();
            chkonwlChDrugsTropism.setType(model.getType())
                    .setSort(model.getSort())
                    .setName(model.getName())
                    .setStatus(1)
                    .setCreateDate(LocalDateTime.now());
            chDrugsTropismList.add(chkonwlChDrugsTropism);
        }
        if (CollectionUtil.isNotEmpty(chDrugsTropismList)) {
            ckonwlChDrugsTropismService.saveBatch(chDrugsTropismList);
        }
    }

    @Override
    public void importDrugCategory(MultipartFile file) {
        if (file == null) {
            throw new ZekeException(400, "请上传文件");
        }
        if (!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            throw new ZekeException(400, "只支持xlsx和xls文件格式");
        }
        List<ExcelAddCategroyModel> list = new ArrayList<>();
        try {
            list = ExtUtils.importExcel(file, 0, 1, ExcelAddCategroyModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }

        if (list == null || list.isEmpty()) {
            throw new ZekeException(400, "文档数据为空");
        }
        List<ChknowlChDrugsCategory> categories = new ArrayList<>();
        for (ExcelAddCategroyModel model : list) {
            String category = model.getName();
            LambdaQueryWrapper<ChknowlChDrugsCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChknowlChDrugsCategory::getName, category.trim())
                    .eq(ChknowlChDrugsCategory::getLevel, 1)
                    .eq(ChknowlChDrugsCategory::getPid, 0)
                    .eq(ChknowlChDrugsCategory::getStatus, 1)
                    .select(ChknowlChDrugsCategory::getId);
            ChknowlChDrugsCategory chknowlChDrugsCategory = categoryService.getOne(wrapper);
            if (chknowlChDrugsCategory == null) {
                continue;
            }
            chknowlChDrugsCategory.setExplains(model.getExplain())
                    .setCategory(model.getCategory());
            if (StringUtils.isNotBlank(model.getCategory())) {
                String[] strs = model.getCategory().split("</br>");
                chknowlChDrugsCategory.setCategoryDesc(strs[0].trim());
                for (int i = 1; i < strs.length; i++) {
                    String[] twoCategoryNames = strs[i].trim().split("：");
                    if (twoCategoryNames.length == 2) {
                        LambdaQueryWrapper<ChknowlChDrugsCategory> qw = new LambdaQueryWrapper<>();
                        qw.eq(ChknowlChDrugsCategory::getName, twoCategoryNames[0].trim())
                                .eq(ChknowlChDrugsCategory::getLevel, 2)
                                .eq(ChknowlChDrugsCategory::getPid, chknowlChDrugsCategory.getId())
                                .eq(ChknowlChDrugsCategory::getStatus, 1)
                                .select(ChknowlChDrugsCategory::getId);
                        ChknowlChDrugsCategory twoCategory = categoryService.getOne(qw);
                        if (twoCategory != null) {
                            twoCategory.setExplains(twoCategoryNames[1].trim());
                            categories.add(twoCategory);
                        }
                    }
                }
            }
            categories.add(chknowlChDrugsCategory);
        }
        if (CollectionUtil.isNotEmpty(categories)) {
            categoryService.updateBatchById(categories);
        }
    }


    public static void getAllFile(File fileInput, List<File> allFileList) {
        // 获取文件列表
        File[] fileList = fileInput.listFiles();
        assert fileList != null;
        for (File file : fileList) {
            if (file.isDirectory()) {
                // 递归处理文件夹
                // 如果不想统计子文件夹则可以将下一行注释掉
                getAllFile(file, allFileList);
            } else {
                // 如果是文件则将其加入到文件数组中
                allFileList.add(file);
            }
        }
    }

    private Integer queryDrugsTwoCategoryId(String[] categories, Integer categoryId) {
        LambdaQueryWrapper<ChknowlChDrugsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChknowlChDrugsCategory::getName, categories[1].trim())
                .eq(ChknowlChDrugsCategory::getStatus, 1)
                .eq(ChknowlChDrugsCategory::getLevel, 2)
                .last("limit 1")
                .select(ChknowlChDrugsCategory::getId, ChknowlChDrugsCategory::getName);
        ChknowlChDrugsCategory chknowlChDrugsCategory = categoryService.getOne(wrapper);
        ChknowlChDrugsCategory newCategory = new ChknowlChDrugsCategory();
        //不存在这个分类名保存一条
        if (chknowlChDrugsCategory == null) {
            newCategory
                    .setName(categories[1].trim())
                    .setLevel(2)
                    .setCreateDate(LocalDateTime.now())
                    .setPid(categoryId)
                    .setStatus(1);
            LambdaQueryWrapper<ChknowlChDrugsCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChknowlChDrugsCategory::getStatus, 1)
                    .eq(ChknowlChDrugsCategory::getLevel, 2)
                    .eq(ChknowlChDrugsCategory::getPid, categoryId)
                    .orderByDesc(ChknowlChDrugsCategory::getSort)
                    .last("limit 1")
                    .select(ChknowlChDrugsCategory::getId, ChknowlChDrugsCategory::getName, ChknowlChDrugsCategory::getSort);
            ChknowlChDrugsCategory drugsCategory = categoryService.getOne(queryWrapper);
            if (drugsCategory == null) {
                newCategory.setSort(1);
            } else {
                newCategory.setSort(drugsCategory.getSort() + 1);
            }
            categoryService.save(newCategory);
            categoryId = newCategory.getId();
        } else {
            categoryId = chknowlChDrugsCategory.getId();
        }
        log.info("分类id:{}", categoryId);
        return categoryId;
    }

    private Integer queryDrugsOneCategoryId(String[] categories) {
        Integer categoryId = null;
        LambdaQueryWrapper<ChknowlChDrugsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChknowlChDrugsCategory::getName, categories[0].trim())
                .eq(ChknowlChDrugsCategory::getStatus, 1)
                .eq(ChknowlChDrugsCategory::getLevel, 1)
                .last("limit 1")
                .select(ChknowlChDrugsCategory::getId, ChknowlChDrugsCategory::getName);
        ChknowlChDrugsCategory chknowlChDrugsCategory = categoryService.getOne(wrapper);
        //不存在这个分类名保存一条
        if (chknowlChDrugsCategory == null) {
            ChknowlChDrugsCategory newCategory = new ChknowlChDrugsCategory();
            newCategory
                    .setName(categories[0].trim())
                    .setLevel(1)
                    .setCreateDate(LocalDateTime.now())
                    .setPid(0)
                    .setStatus(1);
            LambdaQueryWrapper<ChknowlChDrugsCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChknowlChDrugsCategory::getStatus, 1)
                    .eq(ChknowlChDrugsCategory::getLevel, 1)
                    .eq(ChknowlChDrugsCategory::getPid, 0)
                    .orderByDesc(ChknowlChDrugsCategory::getSort)
                    .last("limit 1")
                    .select(ChknowlChDrugsCategory::getId, ChknowlChDrugsCategory::getName, ChknowlChDrugsCategory::getSort);
            ChknowlChDrugsCategory drugsCategory = categoryService.getOne(queryWrapper);
            if (drugsCategory == null) {
                newCategory.setSort(1);
            } else {
                newCategory.setSort(drugsCategory.getSort() + 1);
            }
            categoryService.save(newCategory);
            categoryId = newCategory.getId();
        } else {
            categoryId = chknowlChDrugsCategory.getId();
        }
        log.info("分类id:{}", categoryId);
        return categoryId;
    }

    private List<Integer> getLevelCategory(List<ChknowlChDrugs> drugsList, int level, int type) {
        List<Integer> categoryIds = new ArrayList<>();
        if (type == 1) {
            categoryIds = drugsList.stream().filter(item ->
                    item.getLevel() == level
            ).map(ChknowlChDrugs::getCategoryId).collect(Collectors.toList());
        } else if (type == 2) {
            categoryIds = drugsList.stream().filter(item ->
                    item.getLevel() == level
            ).map(ChknowlChDrugs::getPid).collect(Collectors.toList());
        }

        return categoryIds;
    }

    private Map<Integer, List<ChknowlChDrugs>> getDrugsList(List<ChknowlChDrugs> drugsList) {
        if (CollectionUtil.isNotEmpty(drugsList)) {
            return drugsList.stream().collect(Collectors.groupingBy(ChknowlChDrugs::getCategoryId));
        }
        return new HashedMap();
    }

    public String[] getDrugs(String[] tropismArray) {
        for (int i = 0; i < tropismArray.length; i++) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("'").append(tropismArray[i].trim()).append("'");
            tropismArray[i] = stringBuilder.toString();
        }
        return tropismArray;
    }


}
